//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package cn.ekuma.epos.datalogic.define;


import com.openbravo.data.loader.key.KeyBuilder;
import com.openbravo.data.loader.sentence.PreparedSentence;
import com.openbravo.data.loader.sentence.StaticSentence;
import com.openbravo.data.loader.serialize.serializer.read.SerializerReadString;
import com.openbravo.data.loader.serialize.serializer.write.SerializerWriteString;
import com.openbravo.data.loader.table.I_TableSentenceBuilder;
import e.odbo.data.dao.DataLogic;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.datalogic.define.dao.AppUserStateDAO;
import cn.ekuma.epos.datalogic.define.dao.CloseCashDAO;
import cn.ekuma.epos.datalogic.define.dao.LocationDAO;
import cn.ekuma.epos.datalogic.define.dao.ModuleDAO;
import cn.ekuma.epos.datalogic.define.dao.ResourceDAO;
import cn.ekuma.epos.datalogic.define.dao.RoleDAO;
import cn.ekuma.epos.datalogic.define.dao.UserDAO;
import cn.ekuma.epos.datalogic.define.dao.UserExtDAO;
import cn.ekuma.epos.datalogic.define.dao.erp.SharedOrderDAO;
import cn.ekuma.epos.datalogic.define.dao.sale.ShardTicketDAO;
import cn.ekuma.epos.module.Module;
import com.openbravo.bean.AppUser;
import com.openbravo.bean.AppUserState;
import com.openbravo.bean.CloseCash;
import com.openbravo.bean.Location;
import java.util.List;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.*;
import com.openbravo.format.Formats;
import com.openbravo.pos.bean.AppUserExt;
import com.openbravo.pos.bean.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author adrianromero
 */
public class DataLogicSystem extends DataLogic implements I_DataLogicSystem  {

    protected String m_sInitScript;
    private PreparedSentence m_version;
    private StaticSentence m_dummy;
 
    private Map<String, byte[]> resourcescache;

    private UserExtDAO userExtDAO;
    private UserDAO userDAO;
    private RoleDAO roleDAO;
    private ResourceDAO  resourceDAO;
    private CloseCashDAO closeCashDAO;
    private LocationDAO locationDAO;
    private AppUserStateDAO appUserStateDAO;
    private SharedOrderDAO sharedOrderDAO;
    private ModuleDAO moduleDAO;
	private ShardTicketDAO shardTicketDAO;

    public  DataLogicSystem(I_Session s, I_TableSentenceBuilder builder){
        super(s,builder);
        m_sInitScript = "/com/openbravo/pos/scripts/" + s.getDialect().getName();

        m_version = new PreparedSentence(s, "SELECT VERSION FROM APPLICATIONS WHERE ID = ?", SerializerWriteString.INSTANCE, SerializerReadString.INSTANCE);
        m_dummy = new StaticSentence(s, "SELECT * FROM PEOPLE WHERE 1 = 0");
        
        userExtDAO=new UserExtDAO(s);
        addDaoToMap(userExtDAO);
        
        userDAO=new UserDAO(s);
        addDaoToMap(userDAO);
        
        roleDAO=new RoleDAO(s);
        addDaoToMap(roleDAO);
        
        resourceDAO=new ResourceDAO(s);
        addDaoToMap(resourceDAO);
        
        closeCashDAO=new CloseCashDAO(s);
        addDaoToMap(closeCashDAO);
        
        locationDAO=new LocationDAO(s);
        addDaoToMap(locationDAO);
        
        appUserStateDAO=new AppUserStateDAO(s);
        addDaoToMap(appUserStateDAO);
        
        sharedOrderDAO=new SharedOrderDAO(s);
        
        moduleDAO=new ModuleDAO(s);
        addDaoToMap(moduleDAO);
        
        shardTicketDAO=new ShardTicketDAO (s);
        
        resetResourcesCache();   
        
    }


    public String getInitScript() {
        return m_sInitScript;
    }
    
//    public abstract BaseSentence getShutdown();
    
    public final String findVersion(String app_id) throws BasicException {
        return (String) m_version.find(app_id);
    }
    
    public Module findModuleById(String id) throws BasicException {
    	return moduleDAO.find(KeyBuilder.getKey(id));
    }
    
    public  void execDummy() throws BasicException {
        m_dummy.exec();
    }
    public  List<AppUserExt> listPeopleVisible() throws BasicException {
        return userExtDAO.list();
    }      
    public  AppUser findPeopleByCard(String card) throws BasicException {
        return userDAO.findPeopleByCard(card);
    }   

    public  AppUser findPeopleByName(String name) throws BasicException{
        return userDAO.findPeopleByName(name);
    }

    public  AppUser findPeopleByIMSI(String imsi) throws BasicException{
        return userDAO.findPeopleByIMSI(imsi);
    }
    
    public  AppUser findPeopleByNumberAndPass(String number,String pass) throws BasicException{
        return userDAO.findPeopleByNumberAndPass(number, pass);
    }

    public  String findRolePermissions(String sRole) {
        return roleDAO.findRolePermissions(sRole);
    }

    public  String findRoleOrderTypePermissions(String sRole) {
        return roleDAO.findRoleOrderTypePermissions(sRole);
    }
    
    public  void execChangePassword(String id,String newPassword) throws BasicException {
        userDAO.execChangePassword( id, newPassword);
    }

    @Override
    public  String findRolePermissionsByAdvCode(String advCode) {
        return roleDAO.findRolePermissionsByAdvCode(advCode);
    }
    
    public  void resetResourcesCache() {
        resourcescache = new HashMap<String, byte[]>();      
    }

    public  byte[] getResource(String name) {
        byte[] resource;  
        resource = resourcescache.get(name);
        if (!resourcescache.containsKey(name)/*&&resource == null*/) {
            // Primero trato de obtenerlo de la tabla de recursos
            try {
                resource =resourceDAO.getResource(name);
                resourcescache.put(name, resource);
            } catch (BasicException e) {
                resource = null;
            }
        }
        return resource;
    }
    
    public  void setResource(String name, int type, byte[] data) {
        try {
            resourceDAO.setResource(name, type, data);
            resourcescache.put(name, data);
        } catch (BasicException e) {
        }
    }
    
    public  void setResourceAsBinary(String sName, byte[] data) {
        setResource(sName, 2, data);
    }
    
    public  byte[] getResourceAsBinary(String sName) {
        return getResource(sName);
    }
    
    public  String getResourceAsText(String sName) {
        return Formats.BYTEA.formatValue(getResource(sName));
    }
    
    public  String getResourceAsXML(String sName) {
        return Formats.BYTEA.formatValue(getResource(sName));
    }    
    
   

    public  List<String> listResourceNameByType(int type) throws BasicException{
        return resourceDAO.listResourceNameByType(type);
    }

    public  List<Resource> listResourceByType(int type) throws BasicException{
        return resourceDAO.listResourceByType(type);
    }

    public  int getSequenceCash(String host) throws BasicException { 
        return closeCashDAO.getSequenceCash(host);
    }

    public  CloseCash findActiveCash(String sActiveCashIndex) throws BasicException {
        return closeCashDAO.findActiveCash(sActiveCashIndex);
    }

    @Override
    public CloseCash findPeopleActiveCash(String sActiveCashIndex, int delay) throws BasicException {
         return closeCashDAO.findPeopleActiveCash(sActiveCashIndex,delay);
    }

    
    @Override
    public CloseCash findSystemCash(String cashName) throws BasicException {
        return closeCashDAO.findSystemCash(cashName);
    }

     public  String findLocationName(String iLocation) throws BasicException {
        return locationDAO.findLocationName(iLocation);
    }

	@Override
	public AppUser findPeopleById(String id) throws BasicException {	
		return userDAO.find(KeyBuilder.getKey(id));
	}


	public AppUserState getAppUserState(String id) throws BasicException {
		return appUserStateDAO.find(KeyBuilder.getKey(id));
	}
	
	public int insert(AppUserState state) throws BasicException {
		return appUserStateDAO.insert(state);
	}
    
	public int deleteAppUserState(String userId)throws BasicException {
		return appUserStateDAO.delete(KeyBuilder.getKey(userId));
	}


	public void clearUserRecord(String userId) throws BasicException {
		sharedOrderDAO.unLockOrderByUserID(userId);
		shardTicketDAO.unLockTicketByUser(userId);
	}
	


	@Override
	public String findUserStateProcessPermissions(String m_sRole){
		return roleDAO.findRoleStateProcessPermissions(m_sRole);
	}

	@Override
	public Location findLocation(String m_sInventoryLocation)
			throws BasicException {
		return locationDAO.find(KeyBuilder.getKey(m_sInventoryLocation));
	}
	
	@Override
	public Class transParentClass(Class in) {
		return DateLogicUtils.transParentClass(in);
	}

	@Override
	public void closeCash(Date dNow, Date dNow2, String host,
			String userCashIndex) throws BasicException {
		closeCashDAO.closeCash(dNow, dNow2, host, userCashIndex);	
	}


}
